package handlers

import (
	"github.com/gin-gonic/gin"
	"logi-wms/cache"
	"logi-wms/models"
	"logi-wms/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名或密码不能为空",
		})
		return
	}

	redis_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount > 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}
	var user models.User
	models.DB.Where("username=?", username).Find(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁两个小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserRoleAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	uid, _ := strconv.Atoi(c.PostForm("uid"))

	data := models.UserRole{
		Uid: uid,
		Rid: rid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")

	/*
		SELECT
		  *
		FROM
		  users
		  LEFT JOIN user_roles ON users.id = user_roles.uid
	*/
	var data models.UserRole
	models.DB.Table("users").
		Joins("LEFT JOIN user_roles ON users.id = user_roles.uid").
		Where("user_roles.uid=?", uid).
		Find(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"data": data,
		"msg":  "ok",
	})
	return
}
func RoleNodeList(c *gin.Context) {
	nid := c.Query("nid")

	/*
			SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON nodes.id = role_nodes.nid
	*/
	var data models.RoleNode
	models.DB.Table("users").
		Joins("LEFT JOIN user_roles ON users.id = user_roles.uid").
		Where("user_roles.uid=?", nid).
		Find(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"data": data,
		"msg":  "ok",
	})
	return
}
